﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using Benchmark.Core.Communication.Data.Interface;

namespace Benchmark.Core.Communication.Data.Serialization
{
    public class FormatterBinary: IFormatter
    {

        /// <summary>
        /// Deserializer which converts from bytes to model of type T   
        /// </summary>
        /// <typeparam name="T">Output model Type</typeparam>
        /// <param name="bytes">The byte array which need to be deserialized</param>
        /// <returns>Object of generic type T</returns>
        public T DeserializeFromBytes<T>(byte[] bytes)
        {
            T converted;

              var formatter = new BinaryFormatter();


              using (var stream = new MemoryStream(bytes))
              {


                  converted = (T)formatter.Deserialize(stream);


              }

              return (converted);
        }

        /// <summary>
        /// Serialize the Model of type T into byte
        /// </summary>
        /// <typeparam name="T">Type T of Model</typeparam>
        /// <param name="model">Model to be serialized</param>
        /// <returns></returns>
        public byte[] SerializeToByte<T>(T model)
        {
           
                var formatter = new BinaryFormatter();
                using (var stream = new MemoryStream())
                {
                    formatter.Serialize(stream, model);
                    stream.Seek(0, SeekOrigin.Begin);
                      return stream.ToArray();
                }
        }
    }
}
